<?php

namespace app\common\model\user;

use app\common\model\MoneyLog;
use app\common\model\User;
use think\Db;
use think\Exception;
use think\Model;


class Withdraw extends Model
{


    // 表名
    protected $name = 'user_withdraw';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [

    ];

    public static function init()
    {

    }

    public static function operate($params)
    {
        extract($params);
        Db::startTrans();
        try {
            $user = User::lock(true)->find($user_id);
            if ($user && $money != 0) {
                $insert = [
                    'user_id' => $user_id,
                    'money' => $money,
                ];
                $withdraw = self::create($insert);
                $money = $money * (-1);
                $before = $user->money;
                //$after = $user->money + $money;
                $after = function_exists('bcadd') ? bcadd($user->money, $money, 2) : $user->money + $money;
                //更新会员信息
                $user->save(['money' => $after]);
                //写入日志
                MoneyLog::create(['user_id' => $user_id, 'money' => $money, 'before' => $before, 'after' => $after, 'memo' => $withdraw->id, 'type' => 6, 'content' => "主播提现"]);
                Db::commit();
            } else {
                Db::rollback();
                throw new Exception("当前用户有误,请稍后再试");
            }
        } catch (Exception $exception) {
            Db::rollback();
            throw new Exception($exception->getMessage());
        }

        return $withdraw;
    }

    public function statusList()
    {
        return [0 => "申请中", 1 => "已打款",
//            2 => "已拒绝"
        ];
    }

    public function user()
    {
        return $this->belongsTo('app\common\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
